package org.example;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class QuestionCacheService {
    private final Map<String, CacheEntry> cache = new HashMap<>();
    private static final long DEFAULT_EXPIRATION_MINUTES = 30;

    public void put(String question, String answer) {
        cache.put(question.toLowerCase(), new CacheEntry(answer, System.currentTimeMillis()));
    }

    public String get(String question) {
        CacheEntry entry = cache.get(question.toLowerCase());
        if (entry != null && !isExpired(entry)) {
            return entry.answer;
        }
        return null;
    }

    public void clear() {
        cache.clear();
    }

    private boolean isExpired(CacheEntry entry) {
        long elapsedTime = System.currentTimeMillis() - entry.timestamp;
        return TimeUnit.MILLISECONDS.toMinutes(elapsedTime) > DEFAULT_EXPIRATION_MINUTES;
    }

    private static class CacheEntry {
        String answer;
        long timestamp;

        CacheEntry(String answer, long timestamp) {
            this.answer = answer;
            this.timestamp = timestamp;
        }
    }
}